package bgapi

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"bgs/util"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

// SendMinaSubMessage send  miniprogram subscribe message
type SendMinaSubMessage struct {
	TS   int64 `json:"ts"`
	Data struct {
		AccessToken string                            `json:"access_token"` // 接口调用凭证
		OpenID      string                            `json:"openid"`       // 用户openid
		TemplateID  string                            `json:"template_id"`  // 订阅模板id
		Page        string                            `json:"page"`         // 点击模板卡片后的跳转页面，仅限本小程序内的页面
		Content     map[string]map[string]interface{} `json:"content"`      //
		MinaState   string                            `json:"mina_state"`   // 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
	} `json:"data"`
}

// MinaSubMsgHandler send mini-program message handler
type MinaSubMsgHandler struct {
	slog *zap.SugaredLogger
}

// NewMinaSubMsgHandler create a new handler for mini-program message handler
func NewMinaSubMsgHandler(slog *zap.SugaredLogger) *MinaSubMsgHandler {
	return &MinaSubMsgHandler{
		slog: slog,
	}
}

type subMsgResp struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

// HandleMessage implements the Handler interface.
func (h *MinaSubMsgHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		return nil
	}

	h.slog.Infof("message=>%s", string(m.Body))

	var v SendMinaSubMessage
	if decodeErr := json.NewDecoder(bytes.NewReader(m.Body)).Decode(&v); decodeErr != nil {
		return fmt.Errorf("无法解析申请信息: %v", decodeErr)
	}
	if v.Data.OpenID == "" || v.Data.TemplateID == "" || v.Data.Content == nil {
		h.slog.Info("send subscribe message param error")
		return fmt.Errorf("请求参数错误")
	}
	if v.Data.MinaState == "" {
		v.Data.MinaState = "formal"
	}
	ctx := context.Background()

	api := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", v.Data.AccessToken)

	param := map[string]interface{}{
		"touser":            v.Data.OpenID,
		"template_id":       v.Data.TemplateID,
		"page":              v.Data.Page,
		"data":              v.Data.Content,
		"miniprogram_state": v.Data.MinaState,
		"lang":              "zh_CN",
	}

	body, err := util.GetRequest().Send(ctx, "POST", api, param, nil, 2)
	if err != nil {
		h.slog.Infof("send subscribe message error => %s", err.Error())
		return err
	}
	resp := &subMsgResp{}
	if errR := json.Unmarshal(body, resp); errR != nil {
		h.slog.Infof("send subscribe message error => %s", errR.Error())
		return err
	}
	if resp.Errcode != 0 {
		h.slog.Infof("send subcribe return error => %s ", resp.Errmsg)
		if resp.Errcode != 43101 && resp.Errcode != 47003 && resp.Errcode != 41030 {
			return errors.New(resp.Errmsg)
		}
	}
	return nil
}

